import {Injectable} from '@angular/core';

@Injectable()
export class StorageProvider {

  constructor() {
  }

  write(key: string, value: any) {
    if (value) {
      value = JSON.stringify(value);
    }
    localStorage.setItem(key, value);
  }

  read<T>(key: string): T {
    let value: string = localStorage.getItem(key);

    if (value && value != "undefined" && value != "null") {
      return <T>JSON.parse(value);
    }

    return null;
  }

  remove(key: string) {
    if (!key) {
      throw new Error('Invalid Key Value');
    }
    localStorage.removeItem(key);
  }

  getUserInfo(): any {
    return this.read("userInfo");
  }

  clearUserInfo() {
    localStorage.removeItem("userInfo");
  }
}

@Injectable()
export class SessionStorageService {
  constructor() {
  }

  write(key: string, value: any) {
    if (value) {
      value = JSON.stringify(value);
    }
    sessionStorage.setItem(key, value);
  }

  read<T>(key: string): T {
    let value: string = sessionStorage.getItem(key);

    if (value && value != "undefined" && value != "null") {
      return <T>JSON.parse(value);
    }
    return null;
  }
}
